package com.bolehui.base.handle;

import com.bolehui.base.utils.LogUtil;
import com.bolehui.domain.po.Message;
import com.bolehui.service.ConversationService;
import com.bolehui.service.MessageService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName MyWebSocketHandler
 * @Description
 * @createTime 2025/3/16-12:43
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private MessageService messageService;
    @Autowired
    private ConversationService conversationService;
    // 存储会话和 WebSocketSession 的映射
    private final Map<String, WebSocketSession> sessions = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 客户端连接时，获取用户 ID（假设通过 URL 参数传递）
        String userId = session.getUri().getQuery().split("=")[1];
        sessions.put(userId, session);
        System.out.println("用户 " + userId + " 已连接");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到消息: " + payload);

        // 解析消息
        Message msg = new Gson().fromJson(payload, Message.class);

        // 保存消息到数据库
        messageService.saveMessage(msg);

        // 广播消息给接收者
        // 查找接收者的会话
        String receiverId = msg.getReceiverId().toString();
        WebSocketSession channel = sessions.get(receiverId);
        if (channel == null) {
            // 处理 channel 为 null 的情况
            return; // 或者抛出异常，或者执行其他逻辑
        }
        broadcastMessage(channel, msg);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 客户端断开连接时，移除会话
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            if (entry.getValue().equals(session)) {
                sessions.remove(entry.getKey());
                System.out.println("用户 " + entry.getKey() + " 已断开连接");
                break;
            }
        }
    }

    // 解析消息
    private Message parseMessage(String payload) {
        // 假设消息格式为 JSON: {"conversationId": "123", "content": "你好"}
        return new Gson().fromJson(payload, Message.class);
    }

    /**
     * 广播消息
     * @param channel
     * @param message
     */
    private void broadcastMessage(WebSocketSession channel, Message message) {
        for (WebSocketSession session : sessions.values()) {
            if (session.isOpen()) {
                try {
                    channel.sendMessage(new TextMessage(new Gson().toJson(message)));
                } catch (IOException e) {
                    System.err.println("用户 " + channel + " 不在线");
                }
            }
        }
    }
}
